package com.one.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.one.common.core.constants.Constants;
import com.one.common.core.domain.TableDataInfo;
import com.one.friend.domain.question.Question;
import com.one.friend.domain.question.dto.QuestionQueryDTO;
import com.one.friend.domain.question.es.QuestionES;
import com.one.friend.domain.question.vo.QuestionDetailVO;
import com.one.friend.domain.question.vo.QuestionVO;
import com.one.friend.elasticsearch.QuestionRepository;
import com.one.friend.manager.QuestionCacheManager;
import com.one.friend.mapper.question.QuestionMapper;
import com.one.friend.mapper.user.UserSubmitMapper;
import com.one.friend.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionDTO) {
        //题目列表功能，通过es做缓存
        //先尝试从es拿取数据，没有就从数据库中拿取同时更新到es当中
        long count = questionRepository.count();
        if(count <= 0){
            refreshData();
        }
        //从es中模糊查询
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        Pageable pageable = PageRequest.of(questionDTO.getPageNum() - 1,questionDTO.getPageSize(),sort);
        String keyword = questionDTO.getKeyword();
        Integer difficulty = questionDTO.getDifficulty();
        //做四次判断，没传标题内容和难度，只传标题内容，只传难度，同时传了标题内容和难度
        Page<QuestionES> questionES;
        if(difficulty == null && StrUtil.isEmpty(keyword)){
            questionES = questionRepository.findAll(pageable);
        }else if(difficulty == null){
            questionES = questionRepository.findByTitleOrContent(keyword,keyword,pageable);
        }else if(StrUtil.isEmpty(keyword)){
            questionES = questionRepository.findQuestionByDifficulty(difficulty,pageable);
        }else{
            questionES = questionRepository.findByTitleOrContentAndDifficulty(keyword,keyword,difficulty,pageable);
        }
        if(CollectionUtil.isEmpty(questionES)){
            return TableDataInfo.empty();
        }
        //转换为questionVO
        long total = questionES.getTotalElements();
        List<QuestionES> questionESList = questionES.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList,total);
    }

    @Override
    public QuestionDetailVO detail(long questionId) {
        //从es当中拿取出当前题目的信息,
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if(questionES != null){
            BeanUtil.copyProperties(questionES,questionDetailVO);
            return questionDetailVO;
        }
        //es中不存在从数据库中拿并刷新到es当中
        refreshQuestion();
        Question question = questionMapper.selectById(questionId);
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestion(Long questionId) {
        //首先需要拿到当前题目的顺序
        //才能通过当前题目的id跳转前一题，或者后一题
        //通过redis的list结构可以拿到顺序，u:q:l  - value questionId
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <= 0){
            //redis当中不存在,刷新缓存
            questionCacheManager.refreshQuestionList();
        }
        //返回前一题的questionId
        return questionCacheManager.getPreQuestionId(questionId).toString();
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if(listSize == null || listSize <= 0){
            //redis当中不存在,刷新缓存
            questionCacheManager.refreshQuestionList();
        }
        //返回后一题的questionId
        return questionCacheManager.getNextQuestionId(questionId).toString();
    }

    private void refreshQuestion(){
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }

    private void refreshData() {
        //将数据库中的数据更新到es当中
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionESList);
    }

    @Override
    public List<QuestionVO> getHotQuestionList() {
        Long hotListSize = questionCacheManager.getHotListSize();
        List<Long> hotQuestionIdList;
        if(hotListSize == null || hotListSize <= 0){
            //redis中不存在
            //确定分页
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START,Constants.HOST_QUESTION_LIST_END);
            hotQuestionIdList = questionCacheManager.refreshHotQuestionList();
        }else{
            //存在
            hotQuestionIdList = questionCacheManager.getHotList();
        }
        return assembleQuestionVOList(hotQuestionIdList);
    }

    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if(CollectionUtil.isEmpty(hotQuestionIdList)){
            //没有
            return new ArrayList<>();
        }
        //根据id查title
        List<QuestionVO> questionVOList = new ArrayList<>();
        for (Long questionId:hotQuestionIdList) {
            //还要判断es当中是否可能为空
            QuestionES questionES = questionRepository.findById(questionId).orElse(null);
            QuestionVO questionVO = new QuestionVO();
            BeanUtil.copyProperties(questionES,questionVO);
            questionVOList.add(questionVO);
        }
        return questionVOList;
    }
}
